package net.lesscoding.web.server;

import lombok.extern.slf4j.Slf4j;
import net.lesscoding.utils.ByteBufferUtil;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author eleven
 * @date 2024/10/22 10:02
 * @apiNote
 */
@Slf4j
public class ServerTest {

    /**
     * 阻塞模式下的ServerSocketChannel
     */
    @Test
    public void serverSocketChannelTest() {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1. 创建一个ServerSocketChannel
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();) {

            // 2. 绑定端口
            serverSocketChannel.bind(new InetSocketAddress(8080));
            List<SocketChannel> socketChannels = new ArrayList<>();
            // 3. 监听连接
            while (true) {
                log.info("Connecting...");
                // 4. 接受连接 accept 会阻塞线程
                SocketChannel socketChannel = serverSocketChannel.accept();
                socketChannels.add(socketChannel);
                // 5. 处理连接
                log.info("接受到连接：{}", socketChannel);
                for (SocketChannel channel : socketChannels) {
                    channel.read(buffer);
                    buffer.flip();
                    ByteBufferUtil.debugRead(buffer);
                    buffer.clear();
                }
            }
        } catch (IOException e) {
            log.error("ServerSocketChannelTest error", e);
        }
    }

    /**
     * 非阻塞模式下的ServerSocketChannel
     */
    @Test
    public void botBlockingServerSocketChannelTest() {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1. 创建一个ServerSocketChannel
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();) {
            // 配置非阻塞模式
            serverSocketChannel.configureBlocking(false);
            // 2. 绑定端口
            serverSocketChannel.bind(new InetSocketAddress(8080));
            List<SocketChannel> channels = new ArrayList<>();
            // 3. 监听连接
            while (true) {
                log.debug("Connecting...");
                // 4. 接受连接 accept 会阻塞线程
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    log.debug("接受到连接：{}", socketChannel);
                    channels.add(socketChannel);
                }
                for (SocketChannel channel : channels) {
                    int read = socketChannel.read(buffer);
                    if (read > 0) {
                        buffer.flip();
                        ByteBufferUtil.debugRead(buffer);
                        buffer.clear();
                    }
                }
            }
        } catch (IOException e) {
            log.error("ServerSocketChannelTest error", e);
        }
    }

    /**
     * 使用Selector的ServerSocketChannel
     * 可以避免一直死循环导致CPU占用率太高的问题
     */
    @Test
    public void selectorServerSocketChannelTest() {
        // 1. 创建一个ServerSocketChannel 和 Selector
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
             Selector selector = Selector.open();) {
            // 2. 绑定端口
            serverSocketChannel.bind(new InetSocketAddress(8080));
            // 3. 配置非阻塞模式
            serverSocketChannel.configureBlocking(false);
            // 4. 注册到Selector 并监听连接事件
            SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            // 5. 循环监听事件
            while (selector.select() > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    // 如果这个key不想处理，可以使用cancel取消操作
                    // next.cancel();
                    log.debug("{}", next);
                    if (next.isAcceptable()) {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
                        socketChannel.register(selector, SelectionKey.OP_READ, byteBuffer);
                        log.debug("接收链接 {}", socketChannel);
                    } else if (next.isReadable()) {
                        SocketChannel channel = (SocketChannel) next.channel();
                        ByteBuffer buffer = (ByteBuffer) next.attachment();
                        int read = channel.read(buffer);
                        if (read == -1) {
                            log.info("客户端断开连接");
                            next.cancel();
                        } else {
                            splitBuffer(buffer);
                            // 如果position == limit 说明buffer满了，需要扩容
                            if (buffer.position() == buffer.limit()) {
                                // 扩容
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                next.attach(newBuffer);
                            }
                        }
                        /**
                         * 如果出现远程主机强制关闭连接，可以用这个捕获一下防止导致服务端挂掉
                         * try {
                         *     SocketChannel channel = (SocketChannel) next.channel();
                         *     buffer.clear();
                         *     int read = channel.read(buffer);
                         *     if (read == -1) {
                         *         log.info("客户端断开连接");
                         *         next.cancel();
                         *     }
                         *     buffer.flip();
                         *     log.info("收到消息 {}", new String(buffer.array()));
                         *     buffer.clear();
                         *     channel.close();
                         * } catch (IOException ioe) {
                         *     log.error("关闭失败", ioe);
                         *     next.cancel();
                         * }
                         */
                    } else if (next.isWritable()) {
                        SocketChannel channel = (SocketChannel) next.channel();
                        ByteBuffer buffer = (ByteBuffer) next.attachment();
                        buffer.rewind();
                        channel.write(buffer);
                        next.interestOps(SelectionKey.OP_READ);
                        buffer.clear();
                    }
                    iterator.remove();
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void splitBuffer(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            // 找到一条完整消息
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                // 把这条完整消息存入新的ByteBuffer
                ByteBuffer target = ByteBuffer.allocate(length < 0 ? 16 : length);
                //从source 读，向 target 写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                ByteBufferUtil.debugAll(target);
            }
        }
        source.compact();
    }


    @Test
    public void serverWriteTest() {
        try (Selector selector = Selector.open();
             ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(8080));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (selector.select() > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    iterator.remove();
                    if (next.isAcceptable()) {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < 100000; i++) {
                            stringBuilder.append("A");
                        }
                        ByteBuffer buffer = StandardCharsets.UTF_8.encode(stringBuilder.toString());
                        /**
                         * 数据量太大会导致阻塞
                         *  while (buffer.hasRemaining()) {
                         *      int write = socketChannel.write(buffer);
                         *      log.info("本次写入 {}字节", write);
                         *  }
                         */
                        socketChannel.write(buffer);
                        // 如果还有剩余就在可写状态下执行
                        if (buffer.hasRemaining()) {
                            next.interestOps(next.interestOps() | SelectionKey.OP_WRITE);
                            next.attach(buffer);
                        }
                    } else if (next.isWritable()) {
                        ByteBuffer buffer = (ByteBuffer) next.attachment();
                        SocketChannel channel = (SocketChannel) next.channel();
                        int write = channel.write(buffer);
                        log.info("本次写入 {}字节", write);
                        if (!buffer.hasRemaining()) {
                            next.interestOps(next.interestOps() & ~SelectionKey.OP_WRITE);
                            next.attach(null);
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.error("创建连接失败", e);
        }
    }
}
